<script setup>
import {onMounted, ref, shallowReactive, shallowRef} from "vue";
import router from "../../../router";
import {saveApi} from "../../../api/emp.js";
import {listApi} from "../../../api/dept.js";
import {getResponseData} from "../../../util";
import {RULE} from "../../../const";
import MyNav from "../../../components/MyNav.vue";
import MyForm from "../../../components/MyForm.vue";

/* ==================== 查询全部的部门记录 ==================== */
// 所在部门下拉菜单选项
let deptItems = ref([]);

async function listDept() {
  let res = await listApi();
  let depts = getResponseData(res);
  Object.values(depts).forEach(dept => {
    deptItems.value.push({'label': dept['name'], 'value': dept['id']});
  });
}

/* ==================== 添加表单 ==================== */

// 表单项
let items = shallowRef([
  {'label': '员工姓名', 'prop': 'name', 'required': true, 'span': 12},
  {
    'label': '员工性别', 'prop': 'gender', 'type': 'select', 'required': true, 'span': 12, 'optionItems': [
      {'label': '女', 'value': 0},
      {'label': '男', 'value': 1},
      {'label': '保密', 'value': 2}
    ],
  },
  {'label': '身份证号', 'prop': 'idCard', 'required': true, 'span': 12},
  {'label': '入职日期', 'prop': 'hiredate', 'type': 'date', 'required': true, 'span': 12},
  {'label': '工作岗位', 'prop': 'job', 'required': true, 'span': 12},
  {'label': '电子邮件', 'prop': 'email', 'required': true, 'span': 12},
  {'label': '手机号码', 'prop': 'phone', 'required': true, 'span': 12},
  {'label': '微信号码', 'prop': 'wechat', 'required': true, 'span': 12},
  {'label': '紧急联系人', 'prop': 'emergencyContactName', 'required': true, 'span': 12},
  {'label': '紧急联系电话', 'prop': 'emergencyContactPhone', 'required': true, 'span': 12},
  {
    'label': '所在部门', 'prop': 'deptId', 'type': 'select', 'optionItems': deptItems.value,
    'required': true, 'span': 12
  },
  {'span': 12, 'hidden': true},
  {'label': '详细地址', 'prop': 'address', 'type': 'textarea', 'span': 12},
  {'label': '员工描述', 'prop': 'info', 'type': 'textarea', 'span': 12},
]);
// 表单值
let data = shallowReactive({});
// 表单规则
let rules = {
  'name': RULE.REALNAME,
  'phone': RULE.PHONE,
  'emergencyContactPhone': RULE.PHONE,
  'idCard': RULE.IDCARD,
  'info': RULE.COMMON_INFO,
};

/* ==================== 加载函数 ==================== */
onMounted(() => listDept());

</script>

<template>
  <my-nav :items="[
  {'icon': 'Avatar', 'label': '用户管理', 'url': '/Emp'},
  {'icon': 'User', 'label': '员工列表', 'url': '/Emp'},
  {'icon': 'Plus', 'label': '添加员工'},
]"/>

  <el-divider/>

<el-card class="emp-insert-card" header="添加员工信息">
  <my-form type="insert" v-if="deptItems.length > 0"
           :items="items"
           :data="data"
           :rules="rules"
           :api="saveApi"
           :fn="() => router.push('/Emp')"/>
</el-card>
</template>

<style scoped lang="scss">
.emp-insert-card {
  width: 60%;
  margin: auto;
}
</style>